package com.xxll.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Set;

@Slf4j
@Component
public class JwtCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${no.require.urls:/admin/login,/user/gt/register,/user/login}")
    private Set<String> noRequiredTokenUris;


    /**
     * 过滤器拦截用户的请求后的处理
     * @param exchange
     * @param chain
     **/
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("JwtCheckFilter is starting...");
        // 1、该接口是否需要token才能访问
        if (!isRequiredToken(exchange)) {
            //不需要直接放行
            return chain.filter(exchange);
        }
        // 2、取出用户的token
        String token = getUserToken(exchange);
        // 3、判断用户的token是否有效
        if (StringUtils.isEmpty(token)) {
            return buildedNoAuthorizationResult(exchange);
        }
        Boolean hasToken = redisTemplate.hasKey(token);
        if (hasToken == null || !hasToken) {
            //token 无效
            log.error("token is invalid.");
            return buildedNoAuthorizationResult(exchange);
        }
        return chain.filter(exchange);
    }

    /**
     * 构造没有token的响应结果
     * @param
     * @param exchange
     **/
    private Mono<Void> buildedNoAuthorizationResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type", "application/json");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", "NoAuthorization");
        jsonObject.put("errorMessage", "token is null or empty");
        DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(wrap));
    }

    /**
     * 从请求头里面获取用户的token
     * @param exchange
     **/
    private String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        log.info("token: {}", token);
        return token == null ? null : token.replace("bearer ", "");
    }

    /**
     * 判断该接口是否需要token
     * @param exchange
     **/
    private boolean isRequiredToken(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        log.info("noRequiredTokenUris: {}, path: {}", noRequiredTokenUris, path);
        return !noRequiredTokenUris.contains(path);
    }


    /**
     * 拦截器顺序
     * @param
     **/
    @Override
    public int getOrder() {
        return 0;
    }
}
